package com.wwm.petadopt;

import android.app.ActionBar;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;


public class RegisterActivity extends Activity {
    private EditText editTextUsername;
    private EditText editTextPassword;
    private EditText editTextPasswordConfirm;
    private EditText editTextEmail;
    private Spinner spinnerGender;
    private Spinner spinnerBloodType;
    private Spinner spinnerConstellation;
    private EditText editTextShortMsg;

    private String gender;
    private String bloodtype;
    private String constellation;


    private RequestQueue mRequestQueue;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        ActionBar ab = getActionBar();
        if (ab != null) {
            View actionbarview = getLayoutInflater().inflate(R.layout.actionbar, null);
            ((TextView) actionbarview.findViewById(R.id.text_actionbar)).setText(R.string.register);

            ab.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
            ab.setCustomView(actionbarview);
            Log.i("actionbar", "AccountFragment");
        }
        // Inflate the layout for this fragment


        Button buttonRegister = (Button) findViewById(R.id.button_register);
        Button buttonCancel = (Button) findViewById(R.id.button_cancel);

        editTextUsername = (EditText) findViewById(R.id.edittext_register_username);
        editTextPassword = (EditText) findViewById(R.id.edittext_register_password);
        editTextPasswordConfirm = (EditText) findViewById(R.id.edittext_register_password_confirm);
        editTextEmail = (EditText)findViewById(R.id.edittext_email);
        spinnerGender = (Spinner)findViewById(R.id.spinner_gender);
        spinnerBloodType = (Spinner)findViewById(R.id.spinner_bloodtype);
        spinnerConstellation = (Spinner)findViewById(R.id.spinner_constellation);
        editTextShortMsg = (EditText)findViewById(R.id.edit_shortmessage);

        spinnerGender.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {
                gender = parent.getItemAtPosition(position).toString();
                //Toast.makeText(RegisterActivity.this, "你点击的是:"+str, Toast.LENGTH_SHORT).show();
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // TODO Auto-generated method stub
            }
        });
        spinnerBloodType.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {
                bloodtype = parent.getItemAtPosition(position).toString();
                //Toast.makeText(RegisterActivity.this, "你点击的是:"+str, Toast.LENGTH_SHORT).show();
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // TODO Auto-generated method stub
            }
        });
        spinnerConstellation.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {
                constellation = parent.getItemAtPosition(position).toString();
                //Toast.makeText(RegisterActivity.this, "你点击的是:"+str, Toast.LENGTH_SHORT).show();
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // TODO Auto-generated method stub
            }
        });


        buttonRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username = editTextUsername.getText().toString();
                String password = editTextPassword.getText().toString();
                String passwordConfirm = editTextPasswordConfirm.getText().toString();
                Log.i("LoginEvent", "username: " + username + "; password: " + password + "; confirm " + passwordConfirm);

                if (username.length() == 0 || password.length() == 0 || passwordConfirm.length() == 0)
                {
                    Toast.makeText(v.getContext(), "用户名或密码不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (!password.equals(passwordConfirm)) {
                    Toast.makeText(v.getContext(), "两次输入的密码不同，请再次输入", Toast.LENGTH_SHORT).show();
                    return;
                }

                mRequestQueue = Volley.newRequestQueue(v.getContext());
                Map<String, String> map = new HashMap<String, String>();
                map.put("UserName", username);
                map.put("PassWord", password);
                map.put("Email", editTextEmail.getText().toString());
                map.put("gender", gender);
                map.put("BloodType", bloodtype);
                map.put("Constellation", constellation);
                map.put("ShortMsg", editTextShortMsg.getText().toString());

                JsonObjectRequest jr = new JsonObjectRequest(Request.Method.POST, GlobalData.REGISTER_URL, new JSONObject(map), new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.i("petadopt", response.toString());
                        //parseJSON(response);
                        try {
                            Log.i("petadopt", response.toString());
                            //	Log.i("petadopt", response.getString("success").toString());
                            int loginReqReturnValue = response.getInt("success");
                            Log.i("petadopt", Integer.toString(loginReqReturnValue));
                            if (loginReqReturnValue == 0) {
                                Toast.makeText(RegisterActivity.this, response.getString("message"), Toast.LENGTH_SHORT).show();
                                RegisterActivity.this.finish();
                            }
                            else
                            {Toast.makeText(RegisterActivity.this, response.getString("message"), Toast.LENGTH_SHORT).show();}
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("petadopt", error.getMessage());
                    }
                });
                mRequestQueue.add(jr);
            }
        });

        buttonCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RegisterActivity.this.finish();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_register, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
